import './index.less'
import {WeaInputSearch} from 'ecCom'
import Transfer from './Transfer'

let _this;
class Main extends React.Component{
    constructor(props){
        super(props);
        _this = this;
        this.state = {
            visible: false
        }
    }
    shouldComponentUpdate(nextProps, nextState) {
        return this.state.visible !== nextState.visible
            || this.props.value !== nextProps.value;
    }
    render(){
        const {fieldname,description,options,value} = this.props;
        const {visible} = this.state;
        let newoptions = [];
        let optionmap = {};
        options && options.forEach(item=>{
            newoptions.push({id:item.key, name:item.showname});
            optionmap[item.key] = item.showname;
        });
        let selectedName = "";
        const selectedKeys = !!value ? value.split(",") : new Array();
        selectedKeys && selectedKeys.map(v =>{
            selectedName += optionmap[v]+"  ";
        });
        return (
            <div>
                <WeaInputSearch style={{width:"100%"}} 
                    onSearch={v=>{this.controlModal(true)}} 
                    onSearchChange={this.onSearchChange.bind(this)}
                    value={selectedName} 
                />
                {
                    visible && <Transfer visible={visible} 
                        fieldname={fieldname} 
                        description={description} 
                        options={newoptions} 
                        selectedKeys={selectedKeys} 
                        onConfirm={v=>{this.onConfirm(v)}} 
                        onCancel={v=>{this.controlModal(false)}} 
                    />
                }
            </div>
        )
    }
    onSearchChange(v){
        if(v === ""){
            typeof this.props.onChange == 'function' && this.props.onChange("");
        }
    }
    controlModal(visible){
        this.setState({visible: visible});
    }
    onConfirm(keyArr){
        this.setState({visible: false});
        let valuestr = '';
        keyArr && keyArr.forEach((v,index)=>{
            if(index !== 0)
                valuestr += ",";
            valuestr += v;
        });
        typeof this.props.onChange == 'function' && this.props.onChange(valuestr);
    }
}

export default Main;